import os
import tkinter as tk
from tkinter import filedialog, messagebox, simpledialog, ttk
from PIL import Image
import threading

class ImageResizerApp:
    def __init__(self, root):
        self.root = root
        self.root.title("图片批量压缩软件 V0.1 by 流沙 QQ:541750337")
        self.root.geometry('500x450')  # 设置窗口大小

        # 创建框架
        format_frame = tk.Frame(self.root, pady=20, padx=20)
        format_frame.pack(fill=tk.X)

        input_frame = tk.Frame(self.root, pady=20, padx=20)
        input_frame.pack(fill=tk.X)

        output_frame = tk.Frame(self.root, pady=20, padx=20)
        output_frame.pack(fill=tk.X)

        compression_frame = tk.Frame(self.root, pady=20, padx=20)
        compression_frame.pack(fill=tk.X)

        progress_frame = tk.Frame(self.root, pady=20, padx=20)
        progress_frame.pack(fill=tk.X)

        button_frame = tk.Frame(self.root, pady=20, padx=20)
        button_frame.pack(fill=tk.X)

        # 图片格式选择
        self.format_var = tk.StringVar(value="All")
        formats = ["All", "JPEG", "JPG", "PNG", "GIF", "BMP"]
        tk.Label(format_frame, text="选择要转换的图片格式 (ALL代表所有): ").pack(side=tk.LEFT)
        tk.OptionMenu(format_frame, self.format_var, *formats).pack(side=tk.LEFT, fill=tk.X, expand=False)

        # 输入路径选择
        tk.Button(input_frame, text="源目录: ", command=self.select_input_directory).pack(side=tk.LEFT)
        self.input_directory = tk.StringVar()
        tk.Label(input_frame, textvariable=self.input_directory).pack(side=tk.LEFT, fill=tk.X, expand=True)

        # 输出路径选择
        tk.Button(output_frame, text="输出目录: ", command=self.select_output_directory).pack(side=tk.LEFT)
        self.output_directory = tk.StringVar()
        tk.Label(output_frame, textvariable=self.output_directory).pack(side=tk.LEFT, fill=tk.X, expand=True)

        # 压缩倍数输入
        tk.Button(compression_frame, text="设置压缩系数: ", command=self.set_compression_factor).pack(side=tk.LEFT)
        self.compression_factor = tk.DoubleVar(value=0.1)
        tk.Label(compression_frame, textvariable=self.compression_factor).pack(side=tk.LEFT)

        # 进度条
        self.progress = ttk.Progressbar(progress_frame, orient='horizontal', mode='determinate', length=280)
        self.progress.pack(fill=tk.X)

        # 开始处理按钮
        tk.Button(button_frame, text="开始压缩", command=self.start_resizing).pack(fill=tk.X)

    def select_input_directory(self):
        directory = filedialog.askdirectory()
        if directory:
            self.input_directory.set(directory)

    def select_output_directory(self):
        directory = filedialog.askdirectory()
        if directory:
            self.output_directory.set(directory)

    def set_compression_factor(self):
        factor = simpledialog.askfloat("压缩", "输入压缩系数（例如，0.1 即变为原来的1/10, 0.2即为1/5）:",
                                       minvalue=0.01, maxvalue=1.0)
        if factor:
            self.compression_factor.set(factor)

    def start_resizing(self):
        if not self.input_directory.get() or not self.output_directory.get():
            messagebox.showerror("报错", "请选择源目录和输出目录.")
            return
        if self.compression_factor.get() <= 0 or self.compression_factor.get() > 1:
            messagebox.showerror("报错", "压缩系数必须大于0且小于等于1.")
            return

        # 开启线程
        threading.Thread(target=self.resize_images).start()

    def resize_images(self):
        directory = self.input_directory.get().replace('\\', '/')
        output_directory = self.output_directory.get().replace('\\', '/')
        factor = self.compression_factor.get()
        valid_extensions = {
            "JPEG": ".jpeg",
            "JPG": ".jpg",
            "PNG": ".png",
            "GIF": ".gif",
            "BMP": ".bmp"
        }
        selected_format = self.format_var.get()
        extensions = valid_extensions.values() if selected_format == "All" else [valid_extensions[selected_format]]

        files = [f for f in os.listdir(directory) if any(f.lower().endswith(ext) for ext in extensions)]
        total_files = len(files)
        self.progress['maximum'] = total_files

        for i, filename in enumerate(files):
            filepath = os.path.join(directory, filename)
            with Image.open(filepath) as img:
                new_width = int(img.width * factor)
                new_height = int(img.height * factor)
                img = img.resize((new_width, new_height), Image.Resampling.LANCZOS)

                # 在保存前转换图像模式
                # if img.mode == 'RGBA' and 'jpg' in filename.lower():
                if img.mode == 'RGBA':
                    img = img.convert('RGB')  # 转换为RGB

                output_path = os.path.join(output_directory, f"resized_{filename}")
                if not os.path.exists(output_path):
                    img.save(output_path)
            self.progress['value'] = i + 1
            self.root.update_idletasks()

        messagebox.showinfo("成功", f"成功压缩 {total_files} 张图片.")


def main():
    root = tk.Tk()
    app = ImageResizerApp(root)
    root.mainloop()

if __name__ == "__main__":
    main()
